<?php
class CLayout
{
      public $layout = false;
      public $regions = false;
      function __construct($layout)
      {
            $this->layout = $layout;
      }
      function build_page(&$components)
      {
            $layout = $this->layout;
            $component_groups = CList($components)->group('region');
            foreach($this->regions() as $region)
            {
                  $layout = $this->build_region($layout, $region, isset($component_groups[$region])?$component_groups[$region]:false);
            }
            return $layout;
      }
      function build_region($layout, $region, $components)
      {
            if($components)
            {
                  $code = '<?php ';
                  foreach($components as $component)
                  {
                        $code .= 'CPage::$current->blocks['.$component['id'].']->draw();';
                  }
                  $code .= ' ?>';
            }
            else
            {
                  $code = '';
            }
            return str_replace('[[|'.$region.'|]]',$code,$layout);
      }
      function regions()
      {
            if(!$this->regions)
            {
                  $this->regions = array();
                  if(preg_match_all('/\[\[\|(\w+)\|\]\]/',$this->layout,$patterns))
                  {
                        foreach ($patterns[1] as $region)
                        {
                              $this->regions[] = $region;
                        }
                  }
            }
            return $this->regions;
      }
}
function CLayout($layout)
{
      return new CLayout($layout);
}
?>